/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import data.DataProvider;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *
 * @author bertram
 */
public class kidMaterialer extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        DataProvider prov = new DataProvider();
        PrintWriter out = response.getWriter();

        try {
            if (request.getParameterMap().containsKey("update")) {
                File file = new File("/home/bertram/regin-wsdls/h_Materiale.xml");
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(file);
                doc.getDocumentElement().normalize();
                System.out.println("Root element " + doc.getDocumentElement().getNodeName());
                NodeList nodeLst = doc.getElementsByTagName("row");
                System.out.println("All artists: " + nodeLst.getLength());

                for (int s = 0; s < nodeLst.getLength(); s++) {

                    Node node = nodeLst.item(s);

                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) node;
                        NodeList nl = eElement.getElementsByTagName("cell");
                        Element id = (Element) nl.item(0);
                        int typeId = Integer.parseInt(id.getFirstChild().getNodeValue());
                        Element eTekst = (Element) nl.item(1);
                        String tekst = eTekst.getFirstChild().getNodeValue();
                        System.out.println("id: " + typeId + tekst);
                        //prov.addType(typeId, tekst);
                    }

                }
                System.out.println("DONE!");


            }
 else if(request.getParameterMap().containsKey("tagid")){
     int tagID = Integer.parseInt(request.getParameter("tagid"));
     String tag = prov.getTypeByID(tagID);
     out.write(tag);

 }
         else{
                JSONArray jarr = new JSONArray();
                ArrayList<String> types = prov.getTypes();
                for(int i = 0; i < types.size(); i++){
                   JSONObject obj = new JSONObject();
                   obj.put("index", i +1);//off by one.
                   obj.put("value", types.get(i));
                   jarr.put(obj);
                }
                out.write(jarr.toString());
                System.out.println(jarr.toString());
        }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    private String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }
}
